//
//  CustomTabBarViewController.m
//  CustomTabBar
//
//  Created by Peter Boctor on 1/2/11.
//
// Copyright (c) 2011 Peter Boctor
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE
//

#import "CustomTabBarViewController.h"
#import "NYOPMovieListViewController.h"
#import "CouponMovieListViewController.h"
#import "AccountViewController.h"

#define SELECTED_VIEW_CONTROLLER_TAG 98456345

static NSArray* tabBarItems = nil;

@implementation CustomTabBarViewController

@synthesize tabBar;
@synthesize enableGlow = enableGlow_;

#pragma mark -
#pragma mark - Singleton Methods

static CustomTabBarViewController *sharedTabBarController = nil;

+ (CustomTabBarViewController *)sharedTabBarController
{
    if (sharedTabBarController == nil) {
        sharedTabBarController = [NSAllocateObject([self class], 0, NULL) init];
    }
    
    return sharedTabBarController;
}

+ (id)allocWithZone:(NSZone *)zone
{
    return [[self sharedTabBarController] retain];
}

+ (id)copyWithZone:(NSZone *)zone
{
    return self;
}

- (id)retain
{
    return self;
}

- (NSUInteger)retainCount
{
    return NSUIntegerMax;
}

- (void)release
{
    // do nothing
}

- (id)autorelease
{
    return self;
}

#pragma mark -

- (NSDictionary *)createDictionartWrappingViewControllerOfClass:(Class)aControllerClass 
                                                        nibName:(NSString *)nibName 
                                                backgroundImage:(UIImage *)backgroungImage
{
    UIViewController *viewController = [[aControllerClass alloc] initWithNibName:nibName bundle:nil];
    UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
    viewController.view.backgroundColor = [UIColor colorWithPatternImage:backgroungImage];
    NSDictionary *controllerDict = [NSDictionary dictionaryWithObject:navController forKey:@"viewController"];
    [viewController release];
    //[navController release];
    return controllerDict;
}

- (void)awakeFromNib
{
    // Set up some fake view controllers each with a different background color so we can visually see the controllers getting swapped around
    UIImage *backgroundImage = [UIImage imageNamed:@"background.png"];
    
    NSDictionary *NYOPViewController = [self createDictionartWrappingViewControllerOfClass:[NYOPMovieListViewController class] nibName:@"NYOPMovieListViewController" backgroundImage:backgroundImage];
    NSDictionary *couponViewController = [self createDictionartWrappingViewControllerOfClass:[CouponMovieListViewController class] nibName:@"CouponMovieListViewController" backgroundImage:backgroundImage];
    NSDictionary *accoutViewController = [self createDictionartWrappingViewControllerOfClass:[AccountViewController class] nibName:@"AccountViewController" backgroundImage:backgroundImage];
    
    tabBarItems = [[NSArray arrayWithObjects:NYOPViewController, couponViewController, accoutViewController, nil] 
                   retain];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // Set the background color
    [self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"background.png"]]];
    
    // Set up the selected index to 0
    selectedIndex_ = 0;
    
    // Create a custom tab bar passing in the number of items, the size of each item and setting ourself as the delegate
    self.tabBar = [CustomTabBar  sharedTabBarWithItemCount:3 itemSize:CGSizeMake(self.view.frame.size.width/tabBarItems.count, 48.0f) tag:9999 delegate:self];
    // Place the tab bar at the bottom of our view
    tabBar.frame = CGRectMake(0,
                              self.view.frame.size.height-52.0f,
                              self.view.frame.size.width, 
                              52.0f);
    [self.view addSubview:tabBar];
    
    // Select the first tab
    [tabBar selectItemAtIndex:selectedIndex_];
    
    [self touchDownAtItemAtIndex:selectedIndex_];
}

#pragma mark -
#pragma mark CustomTabBarDelegate

- (UIImage *)imageFor:(CustomTabBar*)tabBar atIndex:(NSUInteger)itemIndex
{
    // No use in this case.
    return nil;
}

- (UIImage *)itemBackgroundImageAtIndex:(NSUInteger)itemIndex
{
    NSString *imageName = nil;
    if (itemIndex == 0) {
        imageName = @"tab_baseL.png";
    }
    else if (itemIndex == 1) {
        imageName = @"tab_baseM.png";
    }
    else {
        imageName = @"tab_baseR.png";
    }
    return [UIImage imageNamed:imageName];
}

- (UIImage *)backgroundImage
{
    return [UIImage imageNamed:@"tabBae_base.png"];
}

// This is the blue background shown for selected tab bar items
- (UIImage *)selectedItemBackgroundImageAtIndex:(NSUInteger)itemIndex
{
    NSString *imageName = nil;
    if (itemIndex == 0) {
        imageName = @"tab_onL.png";
    }
    else if (itemIndex == 1) {
        imageName = @"tab_onM.png";
    }
    else {
        imageName = @"tab_onR.png";
    }
    return [UIImage imageNamed:imageName];
}

// This is the glow image shown at the bottom of a tab bar to indicate there are new items
- (UIImage *)glowImage
{
    // No glow effects
    return nil;
}

// This is the embossed-like image shown around a selected tab bar item
- (UIImage *)selectedItemImage
{
    // Use the TabBarGradient image to figure out the tab bar's height (22x2=44)
    UIImage* tabBarGradient = [UIImage imageNamed:@"TabBarGradient.png"];
    CGSize tabBarItemSize = CGSizeMake(self.view.frame.size.width/tabBarItems.count, tabBarGradient.size.height*2);
    UIGraphicsBeginImageContextWithOptions(tabBarItemSize, NO, 0.0);
    
    // Create a stretchable image using the TabBarSelection image but offset 4 pixels down
    [[[UIImage imageNamed:@"TabBarSelection.png"] stretchableImageWithLeftCapWidth:4.0 topCapHeight:0] drawInRect:CGRectMake(0, 4.0, tabBarItemSize.width, tabBarItemSize.height-4.0)];  
    
    // Generate a new image
    UIImage* selectedItemImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return selectedItemImage;
}

- (UIImage *)tabBarArrowImage
{
    return nil;
}

- (NSString *)titleForItemAtIndex:(NSUInteger)index
{
    if (index == 0) {
        return @"讨价还价";
    }
    else if (index == 1) {
        return @"优惠信息";
    }
    else {
        return @"我的账户";
    }
}

- (void)touchDownAtItemAtIndex:(NSUInteger)itemIndex
{
    // Set the selected index
    selectedIndex_ = itemIndex;
    
    // Remove the current view controller's view
    UIView* currentView = [self.view viewWithTag:SELECTED_VIEW_CONTROLLER_TAG];
    [currentView removeFromSuperview];
    
    // Get the right view controller
    NSDictionary* data = [tabBarItems objectAtIndex:itemIndex];
    UIViewController* viewController = [data objectForKey:@"viewController"];
    
    // Set the view controller's frame to account for the tab bar
    viewController.view.frame = CGRectMake(0.0f,0.0f,self.view.frame.size.width, self.view.frame.size.height-44.0f);
    
    // Se the tag so we can find it later
    viewController.view.tag = SELECTED_VIEW_CONTROLLER_TAG;
    
    // Add the new view controller's view
    [self.view insertSubview:viewController.view belowSubview:tabBar];

}

- (void)addGlowTimerFireMethod:(NSTimer*)theTimer
{
    // Remove the glow from all tab bar items
    for (NSUInteger i = 0 ; i < tabBarItems.count ; i++)
    {
        [tabBar removeGlowAtIndex:i];
    }
    
    // Then add it to this tab bar item
    [tabBar glowItemAtIndex:[[theTimer userInfo] integerValue]];
}

- (void)enableGlowEffect:(BOOL)enable
{
    enableGlow_ = enable;
}

- (void)dealloc
{
    [super dealloc];
    [tabBar release];
}

@end
